<template>
  <div id="picture-search-form">
    <a-form layout="horizontal" :model="searchParams" @finish="doSearch">
      <div class="filter-row">
        <div class="main-filters">
          <a-form-item label="关键词" name="searchText">
            <a-input
              v-model:value="searchParams.searchText"
              placeholder="从名称和简介搜索"
              allow-clear
            />
          </a-form-item>
          <a-form-item label="分类" name="category" style="min-width: 120px">
            <a-auto-complete
              v-model:value="searchParams.category"
              :options="categoryOptions"
              placeholder="请输入分类"
              allowClear
            />
          </a-form-item>
          <a-form-item label="标签" name="tags" style="min-width: 180px">
            <a-select
              v-model:value="searchParams.tags"
              :options="tagOptions"
              mode="tags"
              placeholder="请输入标签"
              allowClear
            />
          </a-form-item>
          <a-form-item label="日期" name="rangeDate">
            <a-range-picker
              v-model:value="dateRange"
              style="width: 400px"
              show-time
              format="YYYY/MM/DD HH:mm:ss"
              :presets="rangePresets"
              @change="onRangeChange"
            />
          </a-form-item>
        </div>
        <a-button type="link" @click="toggleExpand" class="expand-btn">
          {{ expanded ? '收起' : '更多筛选' }}
          <CaretDownOutlined :class="['arrow-icon', { expanded: expanded }]" />
        </a-button>
      </div>

      <a-collapse v-model:activeKey="activeKeys" :bordered="false" class="custom-collapse" ghost>
        <a-collapse-panel key="1" style="border: 0" :showArrow="false">
          <a-space>
            <a-form-item label="名称" name="name">
              <a-input v-model:value="searchParams.name" placeholder="请输入图片名" allow-clear />
            </a-form-item>
            <a-form-item label="简介" name="introduction">
              <a-input
                v-model:value="searchParams.introduction"
                placeholder="请输入简介"
                allow-clear
              />
            </a-form-item>
            <a-form-item label="宽度" name="picWidth">
              <a-input-number v-model:value="searchParams.picWidth" />
            </a-form-item>
            <a-form-item label="高度" name="picHeight">
              <a-input-number v-model:value="searchParams.picHeight" />
            </a-form-item>
            <a-form-item label="图片格式" name="picFormat" style="min-width: 180px">
              <a-auto-complete
                v-model:value="searchParams.picFormat"
                :options="picFormatOptions"
                placeholder="请输入图片格式"
                :filter-option="filterOption"
              />
            </a-form-item>
          </a-space>
        </a-collapse-panel>
      </a-collapse>
      <a-form-item>
        <a-space>
          <a-button type="primary" html-type="submit">搜索</a-button>
          <a-button html-type="reset" @click="doClear">重置</a-button>
        </a-space>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { CaretDownOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
import { listPictureTagCategoryUsingGet } from '@/api/pictureController'
import { message } from 'ant-design-vue'

dayjs.locale('zh-cn')

// 定义上层传入信息接受变量
interface Props {
  onSearch?: (searchParams: API.PictureQueryRequest) => void
}

const props = defineProps<Props>()

//获取图片数据接收
const dataList = ref<API.PictureVO>([]) //记录图片数组
const total = ref(0) // 总图片条数
// 搜索条件
const searchParams = reactive<API.PictureQueryRequest>({})

// 搜索图片数据
const doSearch = () => {
  props.onSearch?.(searchParams)
}

/**
 * 分类和标签输入补充选项数据
 */
const categoryOptions = ref<string[]>([])
const tagOptions = ref<string[]>([])
const picFormatOptions = ref<string[]>([])
picFormatOptions.value = ['PNG', 'JPEG'].map((data: string) => {
  return {
    value: data,
    label: data,
  }
})

// 获取标签和分类选项
const getTagCategoryOptions = async () => {
  const res = await listPictureTagCategoryUsingGet()
  if (res.data.code === 0 && res.data.data) {
    //转换成下拉选项组件接受的格式
    tagOptions.value = (res.data.data.tagList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
    categoryOptions.value = (res.data.data.categoryList ?? []).map((data: string) => {
      return {
        value: data,
        label: data,
      }
    })
  } else {
    message.error('加载选项失败，' + res.data.message)
  }
}

/**
 * 日期表单项
 */
const dateRange = ref<[]>([])

/**
 * 日期范围更改时触发
 * @param dates
 * @param dateStrings
 */
const onRangeChange = (dates: any[], dateStrings: string[]) => {
  //如果范围数据不全，则清空
  if (dates?.length >= 2) {
    // 开始和结束时间都有则转为日期形式传入后端
    searchParams.startEditTime = dates[0].toDate()
    searchParams.endEditTime = dates[1].toDate()
  } else {
    searchParams.startEditTime = undefined
    searchParams.endEditTime = undefined
  }
}

const rangePresets = ref([
  { label: '过去 7 天', value: [dayjs().add(-7, 'd'), dayjs()] },
  { label: '过去 14 天', value: [dayjs().add(-14, 'd'), dayjs()] },
  { label: '过去 30 天', value: [dayjs().add(-30, 'd'), dayjs()] },
  { label: '过去 90 天', value: [dayjs().add(-90, 'd'), dayjs()] },
])

/**
 * 重置按钮：清空所填项
 */
const doClear = () => {
  // 遍历searchParams所有值，设置为空
  Object.keys(searchParams).forEach((key) => {
    searchParams[key] = undefined
  })
  // 日期要单独设置
  dateRange.value = []
  props.onSearch?.(searchParams)
}

onMounted(() => {
  getTagCategoryOptions()
})

/**
 * 折叠筛选项
 */
const activeKeys = ref([])
const expanded = ref(false)

const toggleExpand = () => {
  expanded.value = !expanded.value
  activeKeys.value = expanded.value ? ['1'] : []
}

/* 对于用户输入不区分大小写 **/
const filterOption = (input: string, option: picFormatOptions) => {
  return option.value.toUpperCase().indexOf(input.toUpperCase()) >= 0
}
</script>
<style scoped>
#picture-search-form .ant-form-item {
  margin-top: 15px;
  margin-bottom: 0;
}

/* 主要搜索按钮 */
#picture-search-form .filter-row {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 16px;
}

#picture-search-form .main-filters {
  flex: 1;
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
}

/* 更多按钮样式 */
#picture-search-form .expand-btn {
  flex-shrink: 0;
  padding-right: 0;
}

#picture-search-form .arrow-icon {
  transition: transform 0.3s;
  font-size: 12px;
  margin-left: 4px;
}

#picture-search-form .arrow-icon.expanded {
  transform: rotate(180deg);
}

/* 自定义折叠面板样式 */
#picture-search-form :deep(.custom-collapse) {
  background: transparent;
}

#picture-search-form :deep(.ant-collapse-item) {
  border: 0 !important;
}

#picture-search-form :deep(.ant-collapse-content) {
  border: 0 !important;
  background: transparent;
}

#picture-search-form :deep(.ant-collapse-content-box) {
  padding: 0 !important;
  padding-block: 0 !important;
}

#picture-search-form :deep(.ant-collapse-header) {
  width: 0;
  height: 0;
  padding: 0;
  margin: 0;
}
</style>
